/*
 * Copyright © Jack魏 2022 - 2022 , All Rights Reserved.
 */

package cn.jack1996.yiyi.aop;

import java.util.Map;

import cn.jack1996.yiyi.util.WebUtil;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.log4j.Log4j2;

/**
 * 日志拦截
 *
 * @author Jack魏
 * @since 2022-10-31
 */
@Log4j2
@Aspect
@Component
public class LogAspect {
    /**
     * 指定 controller 包下的注解
     * 一定要注意第一个.. 代表其下面的所有子目录，
     * 最后括号里面的代表所有参数
     */
    @Pointcut("execution(* cn.jack1996.yiyi.controller..*.*(..))")
    public void logPointCut() {
        // Do nothing
    }

    /**
     * 指定当前执行方法在logPointCut之前执行
     */
    @Before("logPointCut()")
    public void doBefore(JoinPoint joinPoint) {
        // 请求内容
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        // 不能为空断言
        assert attributes != null;
        HttpServletRequest request = attributes.getRequest();
        // 请求日志输出
        log.info("------" + WebUtil.getIpAddress(request) + " [" + request.getMethod() + "]"
                + "请求: " + request.getRequestURI());
        logParams(request);
    }

    /**
     * 打印参数信息
     *
     * @param request 请求
     */
    private void logParams(HttpServletRequest request) {
        Map<String, String> parameterMap = WebUtil.getParameterMap(request);
        parameterMap.forEach((key, value) -> log.info("======key:" + key + ", value:" + value));
    }
}
